import { nameDescVerify } from '~/server/validation';
import { SubCategoryModel } from '~/server/models/sub_category.model';
import { MainCategoryModel } from '~/server/models/main_category.model';

/**
 * @api {put} /admin/category/create_sub 创建二级分类
 * @apiName 创建二级分类
 * @apiGroup 分类管理
 * @apiDescription 创建二级分类
 *
 * @apiPermission admin、resource
 *
 * @apiSampleRequest /admin/category/create_sub
 *
 * @apiHeader {String} Authorization 用户 Token
 *
 * @apiBody {String} name 分类名称
 * @apiBody {String} description 权分类描述
 * @apiBody {String} parentId 父级分类 ID
 *
 * @apiSuccess {Number} code 响应状态码
 * @apiSuccess {String} message 响应消息
 * @apiSuccessExample {json} Success-Response:
 * HTTP/1.1 200 OK
 * {
 *   code: 1,
 *   message: '创建成功',
 * }
 */
export default defineEventHandler(async (event) => {
	const checkPermission = checkAdminUserPermission(event, ['admin', 'resource']);
	if (!checkPermission) {
		return {
			code: 0,
			message: '无权访问',
		};
	}

	try {
		const { name, description, parentId } = await readBody(event);

		// 参数校验
		const validation = nameDescVerify.validate({ name, description }).error?.message;
		if (validation && validation !== void 0) {
			return {
				code: 0,
				message: validation,
			};
		}

		// 查询分类是否已存在
		const findResult = await SubCategoryModel.findOne({ name });
		if (findResult !== null) {
			return {
				code: 0,
				message: '分类已存在',
			};
		}

		// 查询父级分类是否存在
		const parentExist = await MainCategoryModel.findById(parentId);
		if (parentExist === null) {
			return {
				code: 0,
				message: '指定的父级分类不存在',
			};
		}

		// 创建分类
		await SubCategoryModel.create({ name, description, parentId });
		return {
			code: 1,
			message: '创建成功',
		};
	} catch (err: any) {
		error(err);
		return {
			code: 0,
			message: err.message,
		};
	}
});
